package org.basis.algorithm.sort;

import org.basis.algorithm.common.SortUtil;

import java.util.PriorityQueue;

/**
 * 堆排序
 *
 * @author Mr_wenpan@163.com 2021/12/06 18:15
 */
public class HeapSort {

    public static void main(String[] args) {
        final int maxSize = 100;
        final int maxValue = 100;
        final int count = 10000;
        for (int i = 0; i < count; i++) {
            int[] array = SortUtil.generateRandomArray(maxSize, maxValue);
            int[] arr = SortUtil.copyArray(array);
            SortUtil.comparator(arr);
            heapSort(array);
            if (!SortUtil.isEqual(arr, array)) {
                SortUtil.printArr(array);
                SortUtil.printArr(arr);
                System.out.println("排序算法有误！");
                break;
            }
        }

    }

    private static void heapSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        // 先构建成大根堆
        for (int i = 0; i < arr.length; i++) {
            heapInsert(arr, i);
        }

        // 每次从大根堆上取堆顶元素，然后新的堆顶重新向下做heapify
        int size = arr.length;
        SortUtil.swap(0, --size, arr);
        while (size > 0) {
            heapify(arr, 0, size);
            SortUtil.swap(0, --size, arr);
        }
    }

    private static void heapInsert(int[] arr, int index) {
        while (arr[index] > arr[(index - 1) / 2]) {
            SortUtil.swap(index, (index - 1) / 2, arr);
            index = (index - 1) / 2;
        }
    }

    private static void heapify(int[] arr, int index, int heapSize) {
        // 左孩子下标
        int left = 2 * index + 1;
        while (left < heapSize) {
            int largest = left + 1 >= heapSize ? left : arr[left] > arr[left + 1] ? left : left + 1;
            // 比他左右孩子都大，则直接break
            if (arr[largest] <= arr[index]) {
                break;
            }
            // 和最大的孩子交换
            SortUtil.swap(largest, index, arr);
            index = largest;
            left = 2 * index + 1;
        }
    }
}
